﻿using JT808.Gateway.Abstractions;
using JT808.Gateway.RabbitMQ.Configs;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;

namespace JT808.Gateway.RabbitMQ
{
    public class JT808NotifyConsumer : IJT808NotifyConsumer
    {
        private bool disposed = false;
        public CancellationTokenSource Cts { get; private set; } = new CancellationTokenSource();
        IOptions<JT808NotifyConsumerConfig> ConsumerConfigAccessor { get; set; }

        private IConnection Connection { get; set; }

        private IChannel Channel { get; set; }
        private String RabbitQueue { get; set; }

        private readonly ILogger logger;

        public string TopicName { get; }

        public JT808NotifyConsumer(
            IOptions<JT808NotifyConsumerConfig> consumerConfigAccessor,
            ILoggerFactory loggerFactory)
        {
            ConsumerConfigAccessor = consumerConfigAccessor;
            TopicName = consumerConfigAccessor.Value.ExchangeName;
            logger = loggerFactory.CreateLogger<JT808NotifyConsumer>();
        }

        public async void OnMessage(Action<(string notifyKey, byte[] param)> callback)
        {
            try
            {
                if (Connection == null)
                {
                    Connection = await ConsumerConfigAccessor.Value.ConnectionFactory.CreateConnectionAsync();
                    Channel = await Connection.CreateChannelAsync();
                    await Channel.ExchangeDeclareAsync(ConsumerConfigAccessor.Value.ExchangeName, ExchangeType.Fanout, durable: true);
                }
                if (RabbitQueue == null || RabbitQueue.Length == 0)
                {
                    RabbitQueue = await Channel.QueueDeclareAsync("JT808NotifyConsumer");
                    await Channel.QueueBindAsync(RabbitQueue, TopicName, string.Empty);
                }
                var consumer = new AsyncEventingBasicConsumer(Channel);
                consumer.ReceivedAsync += (model, ea) =>
                {
                    callback((ea.RoutingKey, ea.Body.ToArray()));
                    return Task.CompletedTask;
                };
                await Channel.BasicConsumeAsync(RabbitQueue, autoAck: true, consumer: consumer);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, TopicName);
            }
        }
        public void Subscribe()
        {
            //consumer.Subscribe(TopicName);
        }
        public void Unsubscribe()
        {
            //if (disposed) return;
            //consumer.Unsubscribe();
            //Cts.Cancel();
        }
        private void Dispose(bool disposing)
        {
            if (disposed) return;
            if (disposing)
            {
                Channel.Dispose();
                Connection.Dispose();
            }
            disposed = true;
        }
        ~JT808NotifyConsumer()
        {
            Dispose(false);
        }
        public void Dispose()
        {
            //必须为true
            Dispose(true);
            //通知垃圾回收机制不再调用终结器（析构器）
            GC.SuppressFinalize(this);
        }
    }
}
